/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/

#ifndef CONNECTIONLISTENER_HPP
#define CONNECTIONLISTENER_HPP

#include "cpputils/TestUtils.hpp"
#include "smartobjects/network/INetworkFactory.hpp"
#include "smartobjects/network/IConnection.hpp"
#include "smartobjects/network/IConnectionListener.hpp"
#include "smartobjects/network/IStreamListener.hpp"

using namespace smartobjects;

class ConnectionListenerTester : public IConnectionListener, public IStreamListener {
public:
	typedef boost::shared_ptr<ConnectionListenerTester> SharedPtr;
public:
	ConnectionListenerTester();
	virtual ~ConnectionListenerTester();
	virtual void onConnected(IConnection* poConnection) throw();
	virtual void onDisconnected(IConnection* poConnection) throw();
	virtual void onReceived(IConnection* poConnection, cpputils::io::ByteBuffer*) throw();
	virtual void onConnectionFailure(IConnection* poConnection, const std::string& sErrorMessage) throw();
	virtual void onReceiveError(IConnection* poConnection, const std::string& sErrorMessage) throw();
	virtual void onWriteError(IConnection* poConnection, const std::string& sErrorMessage) throw();

	void reset();
	bool isConnected();
	std::string getLastErrorMessage();
	ByteBuffer* getLastReceivedMessage();
	const unsigned getReceiveEventCounter();

	boost::mutex& getMonitor();
	void waitForAnyEvent(boost::mutex::scoped_lock& oLock,const std::string& sLocation="Unknown location");
protected:
	void notifyWaiter();
private:
	bool m_bConnected;
	std::string m_sLastErrorMessage;
	unsigned m_nReceiveEventCounter;

	boost::condition m_evAwait;
	boost::mutex m_mxMonitor;
	ByteBuffer* m_poReceiveBuffer;

};

#endif // CONNECTIONLISTENER_HPP
